package cn.iocoder.yudao.module.system.controller.admin.answerRecord;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.module.system.controller.admin.answerRecord.vo.AnswerRecordPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.answerRecord.vo.AnswerRecordRespVO;
import cn.iocoder.yudao.module.system.controller.admin.answerRecord.vo.AnswerRecordSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.ai.UserReportDO;
import cn.iocoder.yudao.module.system.dal.dataobject.answer.UserAnswerDO;
import cn.iocoder.yudao.module.system.dal.dataobject.answerRecord.AnswerRecordDO;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.system.dal.mysql.oauth2.OAuth2AccessTokenMapper;
import cn.iocoder.yudao.module.system.service.ai.UserReportService;
import cn.iocoder.yudao.module.system.service.answer.UserAnswerService;
import cn.iocoder.yudao.module.system.service.answerRecord.AnswerRecordService;
import cn.iocoder.yudao.module.system.util.StringUtilExtend;
import com.xingyuv.jushauth.utils.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;


import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;


import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Tag(name = "管理后台 - 用户回答记录")
@RestController
@RequestMapping("/record/answer-record")
@Validated
public class AnswerRecordController {

    @Resource
    private AnswerRecordService answerRecordService;
    @Resource
    private OAuth2AccessTokenMapper oAuth2AccessTokenMapper;
    @Resource
    private UserAnswerService userAnswerService;
    @Resource
    UserReportService userReportService;

    @PostMapping("/create")
    @Operation(summary = "创建用户回答记录")
    @PreAuthorize("@ss.hasPermission('record:answer-record:create')")
    public CommonResult<Integer> createAnswerRecord(@Valid @RequestBody AnswerRecordSaveReqVO createReqVO) {
        return success(answerRecordService.createAnswerRecord(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新用户回答记录")
    @PreAuthorize("@ss.hasPermission('record:answer-record:update')")
    public CommonResult<Boolean> updateAnswerRecord(@Valid @RequestBody AnswerRecordSaveReqVO updateReqVO) {
        answerRecordService.updateAnswerRecord(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户回答记录")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('record:answer-record:delete')")
    public CommonResult<Boolean> deleteAnswerRecord(@RequestParam("id") Integer id) {
        answerRecordService.deleteAnswerRecord(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得用户回答记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('record:answer-record:query')")
    public CommonResult<AnswerRecordRespVO> getAnswerRecord(@RequestParam("id") Integer id) {
        AnswerRecordDO answerRecord = answerRecordService.getAnswerRecord(id);
        return success(BeanUtils.toBean(answerRecord, AnswerRecordRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户回答记录分页")
    @PreAuthorize("@ss.hasPermission('record:answer-record:query')")
    public CommonResult<PageResult<AnswerRecordRespVO>> getAnswerRecordPage(@Valid AnswerRecordPageReqVO pageReqVO) {
        PageResult<AnswerRecordDO> pageResult = answerRecordService.getAnswerRecordPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, AnswerRecordRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出用户回答记录 Excel")
    @PreAuthorize("@ss.hasPermission('record:answer-record:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportAnswerRecordExcel(@Valid AnswerRecordPageReqVO pageReqVO,
                                        HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AnswerRecordDO> list = answerRecordService.getAnswerRecordPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "用户回答记录.xls", "数据", AnswerRecordRespVO.class,
                BeanUtils.toBean(list, AnswerRecordRespVO.class));
    }

    /**
     * 获取用户的答题记录
     */
    @GetMapping("/getUserAnswerRecord")
    @PermitAll
    public CommonResult<List<AnswerRecordRespVO>> getUserAnswerRecord(@RequestParam("type")Integer type,@RequestParam(value = "recommend",required = false,defaultValue = "false")Boolean recommend) {
        Long loginUserId = getLoginUserId();
        System.out.println("查询到的用户Id: " + loginUserId);

        List<AnswerRecordDO> userAnswerRecord = answerRecordService.getUserAnswerRecord(loginUserId==null?null:loginUserId.intValue(), type,recommend);
        List<AnswerRecordRespVO> bean = BeanUtils.toBean(userAnswerRecord, AnswerRecordRespVO.class);

        if (CollectionUtil.isNotEmpty(bean)) {
            for (AnswerRecordRespVO answerRecordRespVO : bean) {
                List<UserReportDO> userReport = userReportService.getUserReportByUserId(loginUserId,answerRecordRespVO.getId());
                if (CollectionUtil.isNotEmpty(userReport)) {
                    answerRecordRespVO.setReportId(userReport.get(0).getId());
                }
            }
        }

        return success(bean);
    }

    /**
     * 获取用户某组答题记录的答案
     */
    @GetMapping("/getRecordAnswer")
    public CommonResult<Map<Integer, Object>> getRecordAnswerList(HttpServletRequest request, @RequestParam("answerNo") Integer answerNo) {
        String token = request.getHeader("authorization");
        System.out.println("获得的token: " + token);
        String[] tokenArr = token.split(" ");
        OAuth2AccessTokenDO oAuth2AccessTokenDO = oAuth2AccessTokenMapper.selectByAccessToken(tokenArr[1]);
        System.out.println("解析后: " + oAuth2AccessTokenDO);
        Integer userId = oAuth2AccessTokenDO.getUserId().intValue();
        System.out.println("查询到的用户Id: " + userId);
        AnswerRecordDO questionGroupRecord = answerRecordService.getByUserIdAndAnswerNo(userId, answerNo);

        System.out.println("查询到的记录: " + questionGroupRecord);
        //查询记录中的题目
        List<UserAnswerDO> userAnswerDOS = userAnswerService.getAnswerByUserIdAndAnswerNo(userId, answerNo);
        System.out.println("查询到的答题记录: " + userAnswerDOS);
        Map<Integer, Object> groupAnswerMap = new HashMap<>();
        //封装答案
        if (CollectionUtil.isNotEmpty(userAnswerDOS)) {
            for (UserAnswerDO userAnswerDO : userAnswerDOS) {
                System.out.println("查询到的userAnswerDO: "+userAnswerDO);
                if (StringUtils.isNotEmpty(userAnswerDO.getWriteContent())) {
                    groupAnswerMap.put(userAnswerDO.getQuestionId(), userAnswerDO.getWriteContent());
                }
                if (StringUtils.isNotEmpty(userAnswerDO.getAnswerChoices())) {
                    System.out.println("用户的选择: "+userAnswerDO.getAnswerChoices());
                    groupAnswerMap.put(userAnswerDO.getQuestionId(), StringUtilExtend.transferStringToList(userAnswerDO.getAnswerChoices()));
                }
            }
        }
        System.out.println("获得的map: "+groupAnswerMap);
        return success(groupAnswerMap);
    }
}